﻿using Admin.Crypto.Enums;
using Admin.Crypto.Model;

namespace Admin.Crypto.Session
{
    public class UserSession : IUserSession
    {
        private readonly IPrincipalAccessor principal;

        public UserSession(IPrincipalAccessor principalAccessor) 
        { 
            this.principal = principalAccessor;
        }

        public long UserId
        {
            get 
            {
                var strUserId = principal.Principal.FindFirst(ClaimConst.UserId)?.Value;
                if(strUserId == null) 
                    return 0;    

                if(long.TryParse(strUserId, out var userId))
                    return userId;  

                return 0;
            }
        }

        public long? TenantId
        {
            get
            {
                var strValue = principal.Principal.FindFirst(ClaimConst.TenantId)?.Value;
                if (strValue == null)
                    return null;

                if (long.TryParse(strValue, out var value))
                    return value;

                return null;
            }
        }

        public string Account
        {
            get
            {
                var strValue = principal.Principal.FindFirst(ClaimConst.Account)?.Value;
                return strValue ?? string.Empty;
            }
        }

        public string RealName
        {
            get
            {
                var strValue = principal.Principal.FindFirst(ClaimConst.RealName)?.Value;
                return strValue ?? string.Empty;
            }
        }

        public AccountTypeEnum? AccountType
        {
            get
            {
                var strValue = principal.Principal.FindFirst(ClaimConst.AccountType)?.Value;
                if (strValue == null)
                {
                    return null;
                }

                if (int.TryParse(strValue, out var type))
                {
                    return (AccountTypeEnum)type;
                }

                return null;
            }
        }

        public long OrgId
        {
            get
            {
                var strUserId = principal.Principal.FindFirst(ClaimConst.OrgId)?.Value;
                if (strUserId == null)
                    return 0;

                if (long.TryParse(strUserId, out var userId))
                    return userId;

                return 0;
            }
        }

        public string OrgName
        {
            get
            {
                var strValue = principal.Principal.FindFirst(ClaimConst.OrgName)?.Value;
                return strValue ?? string.Empty;
            }
        }

        public string OrgType
        {
            get
            {
                var strValue = principal.Principal.FindFirst(ClaimConst.OrgType)?.Value;
                return strValue ?? string.Empty;
            }
        }
    }
}
